﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using EmoneyWeiXinDAL;
using EmoneyWeiXinCommon;
using EmoneyWeiXinEntity;
using Newtonsoft.Json.Linq;
namespace EmoneyWeiXinBLL
{
    public class TwoCodeManager
    {
        /// <summary>
        /// 查询二维码所有类别
        /// </summary>
        /// <returns></returns>
        public static List<TwoCode_TypeModel> getTwoCodeType(int weixinid)
        {
            return TwoCodeTypeDal.getTwoCodeType(weixinid);
        }
        public static List<TwoCode_TypeModel> getTwoCodeType(int weixinid, int pindex, int psize,out int total)
        {
            return TwoCodeTypeDal.getTwoCodeType(weixinid, pindex, psize,out total);
        }
        /// <summary>
        /// 添加或者修改二维码所有类别
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static int UpdateTwoCodeType(TwoCode_TypeModel obj)
        {
            return TwoCodeTypeDal.UpdateTwoCodeType(obj);
        }

        /// <summary>
        /// 删除二维码所有类别
        /// </summary>
        /// <param name="ID"></param>
        /// <returns></returns>
        public static int deleteTwoCodeType(int ID,int weixinid)
        {
            return TwoCodeTypeDal.deleteTwoCodeType(ID, weixinid);
        }

        /// <summary>
        /// 查询二维码所有信息
        /// </summary>
        /// <returns></returns>
        public static List<TwoCode_InfoModel> getTwoCodeInfo(int weixinid)
        {
            return TwoCodeInfoDal.getTwoCodeInfo(weixinid);
        }
        public static List<TwoCode_InfoModel> getTwoCodeInfo(int size, int pageindex,out int total)
        {
            return TwoCodeInfoDal.getTwoCodeInfo(size, pageindex, null, out total);
        }
        public static List<TwoCode_InfoModel> getTwoCodeInfo(int size, int pageindex, TwoCode_InfoModel obj,out int total)
        {
            return TwoCodeInfoDal.getTwoCodeInfo(size, pageindex, obj, out total);
        }
        /// <summary>
        /// 添加或者修改二维码所有信息
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static int UpdateTwoCodeInfo(TwoCode_InfoModel obj)
        {
            return TwoCodeInfoDal.UpdateTwoCodeInfo(obj);
        }

        /// <summary>
        /// 删除二维码所有信息
        /// </summary>
        /// <param name="ID"></param>
        /// <returns></returns>
        public static int deleteTwoCodeInfo(int ID, int status)
        {
            return TwoCodeInfoDal.deleteTwoCodeInfo(ID, status);
        }

        /// <summary>
        /// 验证区间开始值或结束值是否已经存在其他区间
        /// </summary>
        /// <returns></returns>
        public static bool HasOtherRank(int id, int val, IList<TwoCode_TypeModel> alldata)
        {
            if (id > 0)
                alldata = alldata.Where(p => p.ID != id).ToList();

            foreach (var item in alldata)
            {
                if (val >= item.begin_val && val <= item.end_val)
                    return true;
            }
            return false;
        }
        public static int HasOtherRank2(int id, int begin_val,int end_val, IList<TwoCode_TypeModel> alldata)
        {
            if (id > 0)
                alldata = alldata.Where(p => p.ID != id).ToList();

            foreach (var item in alldata)
            {
                if (begin_val >= item.begin_val && begin_val <= item.end_val)
                    return 1;
                else if (end_val >= item.begin_val && end_val <= item.end_val)
                    return 2;
                else if (begin_val < item.begin_val && end_val > item.end_val)
                    return 3;
            }
            return 0;
        }
        /// <summary>
        /// 验证参数值是否重复
        /// </summary>
        /// <returns></returns>
        public static bool HasReVal(int id, int val, IList<TwoCode_InfoModel> alldata)
        {
            if (id > 0)
                alldata = alldata.Where(p => p.ID != id).ToList();
            alldata = alldata.Where(p => p.value == val).ToList();
            if (alldata != null && alldata.Count > 0)
                return true;
            return false;
        }

        /// <summary>
        /// 获取二维码图片
        /// </summary>
        /// <param name="scene_id"></param>
        /// <returns></returns>
        public static string GetTwoCodeMap(int weixinid, int scene_id)
        {
            var ticket = CreateTwoCodeTicket(weixinid, scene_id);
            return GetTowCodeImagURL(ticket);
        }

        /// <summary>
        /// 创建二维码ticket
        /// </summary>
        /// <param name="scene_id"></param>
        /// <returns></returns>
        public static string CreateTwoCodeTicket(int weixinid, int scene_id)
        {
            string url = Config.WeiXin_ApiUrl + "qrcode/create";
            var msgJson = "{\"action_name\": \"QR_LIMIT_SCENE\", \"action_info\": {\"scene\": {\"scene_id\": " + scene_id + "}}}";
            string funcRet = "";
            try
            {
                weixinUserBLL bll = new weixinUserBLL();
                string appid = bll.getWeixinUserByID(weixinid).AppId;
                string appsercret = bll.getWeixinUserByID(weixinid).AppSecret;
                string token = TokenHelper.GetToken(appid, appsercret);
                if (string.IsNullOrEmpty(token))
                {
                    return funcRet;
                }
                Dictionary<string, string> urlParams = new Dictionary<string, string>();
                urlParams.Add("access_token", token);

                // MyTrace.get().add("调用web服务器-GetTwoCodeTicket-" + url + "||" + msgJson + "||");
                string ret = NetHelper.LoadDataPost(url, urlParams, msgJson, Encoding.UTF8);
                //MyTrace.get().add("调用web服务器-GetTwoCodeTicket-" + ret + "||");
                if (ret.IndexOf("{\"errcode\":40001") != -1)
                {
                    TokenHelper.ClearToken();
                    urlParams = new Dictionary<string, string>();
                    urlParams.Add("access_token", TokenHelper.GetToken(appid, appsercret));
                    ret = NetHelper.LoadDataPost(url, urlParams, msgJson, Encoding.UTF8);
                }

                JObject jObj = JObject.Parse(ret);
                if (jObj != null)
                {
                    JToken jToken;
                    if (jObj.TryGetValue("ticket", out jToken))
                    {
                        funcRet = jObj["ticket"].ToString().Replace("\"", "");
                        ////MyTrace.get().add("调用web服务器-GetTwoCodeTicket-errcode=" + funcRet);
                    }
                }
                ////MyTrace.get().add("funcRet=" + funcRet);
            }
            catch (Exception)
            {
                ////MyTrace.get().add("CreateTwoCodeTicket-Exception:" + ex.Message + " url=" + url + " msgJson=" + msgJson + " scene_id=" + scene_id);
            }
            return funcRet;
        }

        /// <summary>
        /// 获取二维码图片
        /// </summary>
        /// <param name="ticket"></param>
        /// <returns></returns>
        public static string GetTowCodeImagURL(string ticket)
        {
            var ret = "";
            string url = Config.WeiXin_MpUrl + "showqrcode";
            try
            {
               // Dictionary<string, string> urlParams = new Dictionary<string, string>();
                if (!string.IsNullOrEmpty(ticket))
                {
                    ticket = System.Web.HttpUtility.UrlEncode(ticket);
                    ret = string.Concat(url, "?ticket=", ticket); 
                    ////MyTrace.get().add("mpurl=" + u);
                    //return u;
                }
            }
            catch (Exception)
            {
                ////MyTrace.get().add("GetTowCodeImagURL-Exception:" + ex.Message + " ticket=" + ticket);
            }
            return ret;
        }

        public static DataSet searchToCodeLogByType(int type, int size, int index)
        {
            return TwoCodeInfoDal.searchToCodeLogByType(type, size, index);
        }
        public static DataSet searchToCodeLogByParmval(int val, int size, int index)
        {
            return TwoCodeInfoDal.searchToCodeLogByParmval(val, size, index);
        }

        /// <summary>
        /// 根据二维码参数查询二维码消息
        /// </summary>
        /// <param name="val"></param>
        /// <returns></returns>
        public static DataSet searchToCodeInfoByParmval(string val)
        {
            return TwoCodeInfoDal.searchToCodeInfoByParmval(val);
        }
        /// <summary>
        /// 查询随机客服列表
        /// </summary>
        /// <returns></returns>
        public static DataSet searchRandom_KF()
        {
            return TwoCodeInfoDal.searchRandom_KF();
        }

        public static DataSet getWeixinAttentionLogStat(int weixinid, int typeid, int value, int index, int size, out int total)
        {
            return TwoCodeInfoDal.getWeixinAttentionLogStat(weixinid, typeid, value, index, size, out total);
        }

        public static DataSet getWeixinuser_getByTcode(int weixinid, int tcode, int index, int size, out int total)
        {
            return TwoCodeInfoDal.getWeixinuser_getByTcode(weixinid, tcode, index, size, out total);
        }
    }
}
